package com.fenqing.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.json.JSONUtil;
import com.fenqing.bean.Node;

import java.util.List;

public class StringToNodeEncoder implements Encoder<String, Node> {

    @Override
    public Node encoder(String input) {
        List<List<Integer>> lists = JSONUtil.toBean(input, new TypeReference<List<List<Integer>>>() {
        }, true);
        Node[] nodes = new Node[lists.size()];
        for (int i = 0; i < lists.size(); i++) {
            List<Integer> integers = lists.get(i);
            List<Node> neighbors = CollUtil.map(integers, item -> {
                if (nodes[item - 1] == null) {
                    nodes[item - 1] = new Node(item);
                }
                return nodes[item - 1];
            }, true);
            if (nodes[i] == null) {
                nodes[i] = new Node(i + 1);
            }
            nodes[i].neighbors = neighbors;
        }
        return nodes[0];
    }
}
